import { getMongoRepository, } from "typeorm";

import { Select_lessons } from "../models/SelectLesson";

class SelectLessonService {

  // 根据id查询接口
  findById(id: string) {
    const selectLessonRepository = getMongoRepository(Select_lessons);
    return selectLessonRepository.findOne(id)
  }

  // 保存已选课程（选课）
  save(lesson: Select_lessons) {
    const selectLessonRepository = getMongoRepository(Select_lessons);
    return selectLessonRepository.save(lesson)
  }

  // 删除已选课程（退课）
  remove(id: string) {
    const selectLessonRepository = getMongoRepository(Select_lessons);
    return selectLessonRepository.delete(id)
  }

  // 根据课程id、学生学号查询
  findByCidAndStuNum(cid: string, stu_num: string) {
    const selectLessonRepository = getMongoRepository(Select_lessons);
    return selectLessonRepository.findOne({ cid, stu_num })
  }

  // 根据课程名称，教师名称进行模糊查询
  findByNameKey(label: string, value: string, skipNum: number, limit: number, stu_num: string) {
    const selectLessonRepository = getMongoRepository(Select_lessons)
    return selectLessonRepository.find({
      where: {
        [label]: { $regex: value },
        stu_num
      },
      skip: skipNum,
      take: limit
    })
  }
  // 根根据课程名称，教师名称进行模糊查询，总数量
  async findByNameKeyCount(label: string, value: string, stu_num: string) {
    const selectLessonRepository = getMongoRepository(Select_lessons);
    const [users, count] = await selectLessonRepository.findAndCount({
      where: {
        [label]: { $regex: value },
        stu_num
      }
    })
    return count
  }

  // 根据学生姓名模糊查询，和教师id查询
  async findByTidAndStuName(label: string, value: string, skipNum: number, limit: number, tid: string) {
    const selectLessonRepository = getMongoRepository(Select_lessons);
    return selectLessonRepository.find({
      where: {
        [label]: { $regex: value },
        tid,
      },
      skip: skipNum,
      take: limit
    })
  }

  // 根据学生姓名模糊查询，和教师id查询，总数量
  async findByTidAndStuNameCount(label: string, value: string, tid: string) {
    const selectLessonRepository = getMongoRepository(Select_lessons);
    const [users, count] = await selectLessonRepository.findAndCount({
      where: {
        [label]: { $regex: value },
        tid,
      },
    })
    return count
  }

  // 查询学生选择某一教师的所有课程，根据学生学号和教师id查询
  async findAllTeacherCourseWithStu(stu_num: string, tid: string) {
    const selectLessonRepository = getMongoRepository(Select_lessons);
    return selectLessonRepository.find({
      where: {
        stu_num,
        tid,
      },
    })
  }

  // 删除已选课程（教师或管理员删除了课程的情况下）
  deleteManyByCid(cid: string) {
    const selectLessonRepository = getMongoRepository(Select_lessons);
    return selectLessonRepository.deleteMany({ cid })
  }

  // 根据课程id查询
  findByCid(cid: string) {
    const selectLessonRepository = getMongoRepository(Select_lessons);
    return selectLessonRepository.findOne({ cid })
  }
}

export default new SelectLessonService()